
"use strict";
/*--------------------begin chat-dialog------------------------*/
var msgTextarea=chatDialog.find(".body-footer .input")
,	fileType;
function enabledSend() {
	if(msgTextarea.val().length==0) {
		chatDialog.find(".btn.send").attr("disabled","");
		return;
	}
	chatDialog.find(".btn.send").removeAttr("disabled");
}
$(document).ready(function() {
	var selectType=chatDialog.children(".select-type")
	,	selectDialog=chatDialog.children(".select-dialog")
	,	bodyModal=chatDialog.children(".body-modal")
	,	btnImage=chatDialog.find(".btn.image")
	,	btnFile=chatDialog.find(".btn.file")
	,	input=chatDialog.find(".input")
	;
	bodyModal.click(function() {
		$(this).hide();
		selectType.hide();
	});
	chatDialog.children(".body-body").scroll(function() {
		var viewH =$(this).height(),//可见高度
        contentH =$(this).get(0).scrollHeight,//内容高度
        scrollTop =$(this).scrollTop();//滚动高度
        //if(contentH - viewH - scrollTop <= 0) { //到达底部100px时,加载新内容
        if(scrollTop==0) { //到达底部95%时,加载新内容
			// 这里加载数据..
			chatMessageList(currentTalkerID,currentTalkerIsUser);
        }
	});
	btnImage.click(function() {
		fileType="image";
		selectType.hide();
		selectDialog.show();
		input.show();
		input.click();
	});
	btnFile.click(function() {
		fileType="file";
		selectType.hide();
		selectDialog.show();
		input.show();
		input.click();
	});
	chatDialog.find(".btn.confirm").click(function() {
		chatDialog.find("form").submit();
		submitForm();
		bodyModal.hide();
		selectDialog.hide();
	});
	chatDialog.find(".btn.cancle").click(function() {
		bodyModal.hide();
		selectDialog.hide();
	});
	chatDialog.find(".btn.preview").click(function() {
		if(!($("#previewImage"))) {
			$(this).before(`<img class="preview" id="previewImage"></img>`);
		}
	})
});
function submitForm() {
    console.log("submit event");
    var fd = new FormData(document.getElementById("fileinfo"));
    fd.append("token", token);
	fd.append("talkerID",currentTalkerID);
	fd.append("talkerIsUser",currentTalkerIsUser);
	fd.append("fileType",fileType);
	console.log(fd);
    $.ajax({
      url: "/uploadFile",
      type: "POST",
      data: fd,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false// tell jQuery not to set contentType
    }).done(function(res) {
		console.log(res);
		var html="";
		if(res["Code"]!=200) {
			alertDanger(res["Message"]);
			if(fileType=="image") {
				html+=imageMessageRow(userID,iconURL,"image/imageLoadFailed.png",nickname);
			} else if(fileType=="file") {
			}
		} else {
			if(fileType=="image") {
				html+=imageMessageRow(userID,iconURL,res["Result"]["Msg"],nickname);
			} else if(fileType=="file") {
				html+=fileMessageRow(userID,iconURL,res["Result"]["Msg"],nickname);
			}
		}
		var body=chatDialog.children(".body-body");
		body.append(html);
		body.scrollTop(body.get(0).scrollHeight)
    });
    return false;
}
function fileMessageRow(senderID,iconURL,msgContent,nickname) {
	var html;
	if(senderID==userID) {
		var html=`<div class="message">
			<div class="text user">`+msgContent+`</div>
			<img class="icon user" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img>
			<div class="clear"></div>
		</div>`;
	} else {
		var html=`<div class="message">
			<img class="icon friend" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img> `
			if(!currentTalkerIsUser) {
				html+=`<p class="nickname" >`+nickname+`</p>`;
			}
			html+=`<div class="text friend" >`+msgContent+`</div>
			<div class="clear"></div>
		</div>`;
	}
	return html;
}
function messageRow(senderID,iconURL,msgContent,nickname) {
	var html;
	if(senderID==userID) {
		var html=`<div class="message">
			<div class="text user">`+msgContent+`</div>
			<img class="icon user" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img>
			<div class="clear"></div>
		</div>`;
	} else {
		var html=`<div class="message">
			<img class="icon friend" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img> `
			if(!currentTalkerIsUser) {
				html+=`<p class="nickname" >`+nickname+`</p>`;
			}
			html+=`<div class="text friend" >`+msgContent+`</div>
			<div class="clear"></div>
		</div>`;
	}
	return html;
}
function imageMessageRow(senderID,iconURL,msgContent,nickname) {
	var html;
	if(senderID==userID) {
		var html=`<div class="message">
			<img class="text user" src="/`+msgContent+`?token=`+token+`" onclick="showBigImage(this);" onerror="loadImageFailed(this);"></img>
			<img class="icon user" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img>
			<div class="clear"></div>
		</div>`;
	} else {
		var html=`<div class="message">
		<img class="icon friend" src="`+iconURL+`" onclick="personData(event,'`+senderID+`');"></img> `
		if(!currentTalkerID) {
			html+=`<p class="nickname" >`+nickname+`</p>`;
		}
		html+=`<img class="text friend" src="/`+msgContent+`?token=`+token+`" onclick="showBigImage(this);" onerror="loadImageFailed(this);"></img>
			<div class="clear"></div>
			</div>`;
	}
	return html;
}
function showBigImage(obj)
{
	var bodyModal= $(".body-container>.body-modal");
	bodyModal.show();
	var bigImage=bodyModal.children(".big-image")
	,	maxWidth=bodyModal.width()
	,	maxHeight=bodyModal.height();
	bigImage.css({"width":"auto","height":"auto"}).attr("src",obj.src);
	var width=bigImage.width()
	,	height=bigImage.height();
	if(width>maxWidth) {
		bigImage.css({"width":maxWidth,"height":"auto"});
	} else if(height>maxHeight) {
		bigImage.css({"height":maxHeight,"width":"auto"});
	}
	bigImage.show();
	setCenter(bigImage);
	var src=obj.src
	if(src.indexOf('?')==-1) {
		src+="?"
	} else {
		src+="&"
	}
	bigImage.attr("src",src+"compress=false");
}
$(".body-container>.body-modal").click(function() {
	$(this).hide();
	$(".big-image").hide();
});
function loading(obj) {
	$(obj).css("background-image","url('image/loading.gif')");
}
function loadImageFailed(obj) {
	$(obj).attr("src","image/imageLoadFailed.png");
}

// /chatMessageList接口 接收消息后处理函数
function showSelectType() {
	chatDialog.children(".select-type").show();
	chatDialog.children(".body-modal").show();
}
function showChatMessageList(list) {
	if(!list) { 
		alertWarning("已显示全部消息！");
		return;
	}
	var body = chatDialog.children(".body-body");
	for(var i=0;i<list.length;i++) {
		var listRow = list[i];
		var iconURL=listRow["IconURL"]
		,	msgContent = listRow["MsgContent"]
		,	msgType = listRow["MsgType"]
		,	nickname = listRow["Nickname"]
		,	sendTime = listRow["SendTime"]
		,	senderID = listRow["SenderID"]
		,	html=""
		;
		if(msgType=="text") {
			html+=messageRow(senderID,iconURL,msgContent,nickname);
		} else if(msgType=="image") {
			html+=imageMessageRow(senderID,iconURL,msgContent,nickname);
		} else {
			html+=fileMessageRow(senderID,iconURL,msgContent,nickname);
		}
		body.prepend(html);
	}
	messageIndex++;
}
function sendTextMessage() {
	var msg=msgTextarea.val();
	if(msg.length==0) {
		alertDanger("禁止发送空消息！");
		return;
	}
	ws.send(JSON.stringify({
			Method: "/sendTextMessage",
			Args: {
				msgContent: msg,
				talkerID: currentTalkerID,
				talkerIsUser: currentTalkerIsUser
			}
		}));
	var html=messageRow(userID,iconURL,msg,nickname);
	var body = chatDialog.children(".body-body");
	body.append(html);
	msgTextarea.val("");
	chatDialog.find(".send").attr("disabled","");
	body.scrollTop(body.get(0).scrollHeight);
	msgTextarea.focus();
}
// 打开聊天窗口
function showChatDialog(nickname,id,isUser) {
	bodyContainer.children().hide();
	setCookie("page","chat-dialog");
	chatDialog.children(".body-body").html("");
	chatDialog.show();
	messageIndex=0;
	currentTalkerID = id;
	currentTalkerIsUser = isUser;
	chatDialog.find(".body-header .title").html((isUser==true?"正在和":"")+nickname+(isUser==true?"聊天":""));
	chatMessageList(id,isUser);
}
function receiveMessage(res) {
	var id
	,	time
	,	icon
	,	name
	,	msg
	,	msgID
	,	type = res["Type"]
	,	contentType = res["ContentType"]
	,	content = res["Content"]
	,	senderID
	;
	time=content["CreateTime"];
	msg=content["Msg"];
	msgID=content["MsgID"];
	if(type==1) {
		id=senderID=content["FriendID"];
		icon=content["FriendIcon"];
		name=content["FriendName"];
	} else if(type==2) {
		id=content["GroupID"];
		senderID=["SenderID"];
		icon=["SenderIcon"];
		name=["SenderName"];
	} else alertDanger("error message type");
	if(id!=currentTalkerID) {
		return;
	}
	switch(contentType)
	{
		case "text":
			messageRow(senderID,icon,msg,name);
			break;
		case "image":
			imageMessageRow(senderID,icon,msg,name);
			break;
		default:
			alertDanger(contentType+" 功能正在开发中！");
			break;
	}
}
/*-----------------------end chat-dialog----------------------------*/